package com.ljfiction.book.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ljfiction.book.Baner.MyshupingBean;
import com.ljfiction.book.Dialog.IsOrNoDialog;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.R;
import com.ljfiction.book.activitys.LoginActivity;
import com.ljfiction.book.activitys.OtherfensiActivity;
import com.ljfiction.book.activitys.ShupingDatasActivity;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.TimeTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.autolayout.utils.AutoUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by admin on 2017/9/21.
 */

public class MyshupingFragment extends BaseFragment {
    private RecyclerView myshupingrecycler;
    private SmartRefreshLayout refreshMyshupingrecycle;
    private LinearLayout zanwushuju;
    private int page = 1;
    private List<MyshupingBean.DataBean.ListBean> listBean = new ArrayList<>();
    private BaseQuickAdapter shupingItemAdapter;
    private Context context;
    private IsOrNoDialog isOrNoDialog;
    private MyshupingBean myshupingBean;
    private Intent intent;
    private int type = 0;
    private String userId;

    public static MyshupingFragment newInstance(int type,String userId) {
        MyshupingFragment newFragment = new MyshupingFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        bundle.putString("userId",userId);
        newFragment.setArguments(bundle);
        return newFragment;

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.myshuping_recycaler, null);
        myshupingrecycler = view.findViewById(R.id.myshupingrecycler);
        refreshMyshupingrecycle = view.findViewById(R.id.refresh_myshupingrecycle);
        zanwushuju = view.findViewById(R.id.zanwushuju);
        context = getActivity();
        Bundle args = getArguments();
        if (args != null) {
            type =  args.getInt("type");
            userId=args.getString("userId");
        }else {
            showToast("数据传值错误");
            getActivity().finish();
        }
        intView();
        intData();
        return view;
    }

    private void intData() {
        OkHttpUtils.post(HttpManager.IP + "/comm-commInfoByUserId")

                .params("userid", userId)
                .params("startPage", String.valueOf(page))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        refreshMyshupingrecycle.finishLoadMore();
                        refreshMyshupingrecycle.finishRefresh();
                        try {
                            myshupingBean = gson.fromJson(s, MyshupingBean.class);
                            if (myshupingBean.getReturnCode() == 200) {
                                listBean.addAll(myshupingBean.getData().getList());
                                shupingItemAdapter.notifyDataSetChanged();
                                if (listBean.size() < 1) {
                                    zanwushuju.setVisibility(View.VISIBLE);
                                } else {
                                    zanwushuju.setVisibility(View.GONE);
                                }
                            } else {

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    private void intView() {
        myshupingrecycler.setAdapter(shupingItemAdapter = new BaseQuickAdapter<MyshupingBean.DataBean.ListBean, BaseViewHolder>(R.layout.myshupingitem, listBean) {
            @Override
            protected void convert(BaseViewHolder helper, MyshupingBean.DataBean.ListBean item) {
                AutoUtils.autoSize(helper.itemView);
                helper.setText(R.id.content_myshuping, item.getCommentContext())
                        .setText(R.id.myshuping_myname, item.getPseudonym())
                        .setText(R.id.shupingbookname, "《" + item.getBookName() + "》")
                        .setText(R.id.mushupingtime, TimeTool.getTimeAndChange(String.valueOf(item.getCommentDateTime())))
                        .setText(R.id.selectnum, String.valueOf(item.getThumbsCount()))
                        .setText(R.id.shupingdenglimy, "LV" + item.getUserGrade())
                        .setText(R.id.pinglunnum, String.valueOf(item.getReplyCount()));
                Glide.with(mContext).load(item.getUserHeadPortraitURL()).override(ScreenUtils.getNum(mContext,52), ScreenUtils.getNum(mContext,52)).into((ImageView) helper.getView(R.id.myshuping_muimage));
                if (item.getUserSex() == 0) {
                    ((ImageView) helper.getView(R.id.myshupingsex)).setImageResource(R.mipmap.sex_n);
                } else {
                    ((ImageView) helper.getView(R.id.myshupingsex)).setImageResource(R.mipmap.sex_v);
                }
                if (item.getVipGrade() > 0) {
                    helper.getView(R.id.isvipimage_shuping).setVisibility(View.VISIBLE);
                } else {
                    helper.getView(R.id.isvipimage_shuping).setVisibility(View.GONE);
                }
                if (item.getIsthumbs() == 1) {
                    ((ImageView) helper.getView(R.id.dianzanimage)).setImageResource(R.mipmap.good);
                } else {
                    ((ImageView) helper.getView(R.id.dianzanimage)).setImageResource(R.mipmap.goodno);
                }
                helper.addOnClickListener(R.id.dianzanimage);
                if (type == 1) {
                    helper.getView(R.id.deletmyshuping).setVisibility(View.INVISIBLE);
                } else {
                    helper.addOnClickListener(R.id.deletmyshuping);
                }

            }
        });
        myshupingrecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        myshupingrecycler.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL_LIST));

        shupingItemAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(final BaseQuickAdapter adapter, View view, final int position) {
                switch (view.getId()) {
                    case R.id.dianzanimage:
                        if (!UserManageBean.isLogin(context)) {
                            return;
                        }
                        OkHttpUtils.post(HttpManager.IP + "/comm-GiveThumbs")

                                .params("commentId", listBean.get(position).getId())
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(s);
                                            if (jsonObject.getInt("returnCode") == 200) {
                                                if (listBean.get(position).getIsthumbs() == 0) {
                                                    listBean.get(position).setIsthumbs(1);
                                                    listBean.get(position).setThumbsCount(listBean.get(position).getThumbsCount() + 1);
                                                } else {
                                                    listBean.get(position).setIsthumbs(0);
                                                    listBean.get(position).setThumbsCount(listBean.get(position).getThumbsCount() - 1);
                                                }
                                                shupingItemAdapter.notifyDataSetChanged();
                                            }else if (jsonObject.getInt("returnCode") == 400){
                                                Intent intent=new Intent(context, LoginActivity.class);
                                                startActivity(intent);
                                                showToast(jsonObject.getString("msg"));
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                    }
                                });
                        break;
                    case R.id.deletmyshuping:
                        isOrNoDialog = new IsOrNoDialog(context, "确定删除这条评论？", true);
                        isOrNoDialog.setListener(new IsOrNoDialog.Listener() {
                            @Override
                            public void okClick() {
                                OkHttpUtils.post(HttpManager.IP + "/comm-delcomminfo")

                                        .params("id", String.valueOf(listBean.get(position).getId()))
                                        .params("type", "0")
                                        .execute(new StringCallback() {
                                            @Override
                                            public void onSuccess(String s, Call call, Response response) {
                                                try {
                                                    JSONObject jsonObject = new JSONObject(s);
                                                    if (jsonObject.getInt("returnCode") == 200) {
                                                        listBean.remove(position);
                                                        shupingItemAdapter.notifyDataSetChanged();
                                                    }
                                                    showToast(jsonObject.getString("msg"));
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        });
                            }

                            @Override
                            public void closeClick() {

                            }
                        });
                        break;
                }

            }
        });
        shupingItemAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                intent = new Intent(context, ShupingDatasActivity.class);
                intent.putExtra("thisshuping", listBean.get(position));
                startActivity(intent);
            }
        });
        refreshMyshupingrecycle.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (myshupingBean.getData().isIsLastPage()) {
                    refreshMyshupingrecycle.finishLoadMore();
                    refreshMyshupingrecycle.setEnableLoadMore(false);
                } else {
                    page++;
                    intData();
                }
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                listBean.clear();
                refreshMyshupingrecycle.setEnableLoadMore(true);
                intData();
            }
        });
    }


}
